"""
数据模型

定义云盘文件和配置的数据结构。
"""

from enum import Enum
from typing import Dict, Any, Optional, List
from pydantic import BaseModel, Field
from datetime import datetime


class FileType(str, Enum):
    """文件类型枚举"""
    FILE = "file"
    FOLDER = "folder"


class CloudFile(BaseModel):
    """云盘文件信息"""
    file_id: str = Field(..., description="文件ID")
    name: str = Field(..., description="文件名")
    path: str = Field(..., description="文件路径")
    size: int = Field(default=0, description="文件大小(字节)")
    file_type: FileType = Field(..., description="文件类型")
    is_dir: bool = Field(default=False, description="是否为目录")
    modified_time: Optional[str] = Field(default=None, description="修改时间")
    created_time: Optional[str] = Field(default=None, description="创建时间")
    parent_id: Optional[str] = Field(default=None, description="父目录ID")
    download_url: Optional[str] = Field(default=None, description="下载链接")
    
    class Config:
        use_enum_values = True
    
    def is_dir(self) -> bool:
        """是否为目录"""
        return self.file_type == FileType.FOLDER
    
    def is_file(self) -> bool:
        """是否为文件"""
        return self.file_type == FileType.FILE
    
    def format_size(self) -> str:
        """格式化文件大小"""
        if self.size < 1024:
            return f"{self.size} B"
        elif self.size < 1024 * 1024:
            return f"{self.size / 1024:.2f} KB"
        elif self.size < 1024 * 1024 * 1024:
            return f"{self.size / (1024 * 1024):.2f} MB"
        else:
            return f"{self.size / (1024 * 1024 * 1024):.2f} GB"
    
    def format_time(self, time_type: str = "modify") -> str:
        """格式化时间"""
        time_str = self.modified_time if time_type == "modify" else self.created_time
        if not time_str:
            return "未知"
        
        try:
            # 尝试解析时间字符串
            if "T" in time_str:
                dt = datetime.fromisoformat(time_str.replace("Z", "+00:00"))
            else:
                dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
            return dt.strftime("%Y-%m-%d %H:%M:%S")
        except:
            return time_str


class UploadResult(BaseModel):
    """上传结果"""
    success: bool = Field(..., description="是否成功")
    file_id: str = Field("", description="文件ID")
    message: str = Field("", description="消息")
    rapid_upload: bool = Field(False, description="是否秒传")
    
    def __str__(self) -> str:
        status = "成功" if self.success else "失败"
        rapid_info = " (秒传)" if self.rapid_upload else ""
        return f"上传{status}{rapid_info}: {self.message}"


class DownloadResult(BaseModel):
    """下载结果"""
    success: bool = Field(..., description="是否成功")
    local_path: str = Field("", description="本地路径")
    message: str = Field("", description="消息")
    
    def __str__(self) -> str:
        status = "成功" if self.success else "失败"
        return f"下载{status}: {self.message}"


class ProviderConfig(BaseModel):
    """提供者配置"""
    type: str = Field(..., description="提供者类型")
    name: str = Field(..., description="提供者名称")
    config: Dict[str, Any] = Field(default_factory=dict, description="提供者配置")
    enabled: bool = Field(default=True, description="是否启用")
    created_at: Optional[str] = Field(default=None, description="创建时间")
    updated_at: Optional[str] = Field(default=None, description="更新时间")
    
    class Config:
        schema_extra = {
            "examples": [
                {
                    "type": "tianyi_pc",
                    "name": "天翼云盘PC版",
                    "enabled": True,
                    "config": {
                        "username": "your_username",
                        "password": "your_password",
                        "root_folder_id": "-11",
                        "order_by": "filename",
                        "order_direction": "asc",
                        "upload_thread": "3",
                        "rapid_upload": True
                    }
                },
                {
                    "type": "tianyi_tv",
                    "name": "天翼云盘TV版",
                    "enabled": True,
                    "config": {
                        "access_token": "",
                        "root_folder_id": "-11",
                        "order_by": "filename",
                        "order_direction": "asc",
                        "type": "personal",
                        "family_id": "",
                        "upload_thread": "3",
                        "rapid_upload": True
                    }
                }
            ]
        }


class CloudSDKConfig(BaseModel):
    """云盘SDK配置"""
    providers: List[ProviderConfig] = Field(default_factory=list, description="提供者配置列表")
    session_path: str = Field("sessions", description="会话保存路径")
    log_level: str = Field("INFO", description="日志级别")
    
    class Config:
        schema_extra = {
            "example": {
                "providers": [
                    {
                        "type": "tianyi_pc",
                        "name": "天翼云盘PC版",
                        "enabled": True,
                        "config": {
                            "username": "your_username",
                            "password": "your_password",
                            "root_folder_id": "-11",
                            "order_by": "filename",
                            "order_direction": "asc",
                            "upload_thread": "3",
                            "rapid_upload": True
                        }
                    },
                    {
                        "type": "tianyi_tv",
                        "name": "天翼云盘TV版",
                        "enabled": True,
                        "config": {
                            "access_token": "",
                            "root_folder_id": "-11",
                            "order_by": "filename",
                            "order_direction": "asc",
                            "type": "personal",
                            "family_id": "",
                            "upload_thread": "3",
                            "rapid_upload": True
                        }
                    }
                ],
                "session_path": "sessions",
                "log_level": "INFO"
            }
        }